package com.hqyj.am.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hqyj.am.dao.ScheduleMapper;
import com.hqyj.am.dao.UserMapper;
import com.hqyj.am.pojo.ResultVo;
import com.hqyj.am.pojo.Schedule;
import com.hqyj.am.pojo.User;
import com.hqyj.am.pojo.WorkNote;
import com.hqyj.am.dao.WorkNoteMapper;
import com.hqyj.am.service.IWorkNoteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 *  考情管理服务实现类
 *
 * @author rock
 * @since 2022-08-16
 */
@Service
public class WorkNoteServiceImpl extends ServiceImpl<WorkNoteMapper, WorkNote> implements IWorkNoteService {

    @Resource
    private WorkNoteMapper workNoteMapper;

    @Resource
    private ScheduleMapper scheduleMapper;

    @Resource
    private UserMapper userMapper;

    /**
     * 员工签到
     * @param user
     * @return
     */
    @Override
    public ResultVo addWorkTime(User user) {
        System.out.println(user);
        int userId = user.getUserId();
        int departmentId = user.getDepartmentId();
        ResultVo rv = new ResultVo();
        System.out.println(userId);
        System.out.println(departmentId);
        QueryWrapper<WorkNote> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        //倒序查询
        qw.orderByDesc("date");
        //存储该用户的所有记录
        List<WorkNote> workNoteList = workNoteMapper.selectList(qw);
        System.out.println(workNoteList);

        //如果有签到记录
        if(workNoteList.size()!=0){
            //最新记录
            WorkNote workNote = workNoteList.get(0);
            System.out.println(workNote);
            //当前时间
            Calendar rightNow = Calendar.getInstance();
            Date nowTime = rightNow.getTime();
            //当前日期
            LocalDate localDate = LocalDate.now();
            //如果今天重复签到
            if(workNote.getWorkTime()!=null && isSameDay(workNote.getWorkTime(), nowTime)){
                rv.setInfo("您今天已签到，请勿重复签到");
                rv.setSuccess(true);
                return rv;
            }
        }

        //没有签到，则添加签到记录
        WorkNote workNote1 = new WorkNote();
        workNote1.setUserId(userId);
        workNote1.setUserName(user.getUserName());
        workNote1.setDate(LocalDate.now());
        LocalDateTime nowTime1= LocalDateTime.now();
        workNote1.setWorkTime(nowTime1);
        workNote1.setLack(1);
        workNote1.setEarly(0);
        workNote1.setLate(0);

        //获取签到时间标准
        QueryWrapper<Schedule> qw1 = new QueryWrapper<>();
        qw1.eq("department_id", departmentId);
        Schedule schedule = scheduleMapper.selectOne(qw1);
        //如果员工迟到  nowTime.isAfter()在设定的时间之后
        if(nowTime1.isAfter(schedule.getScheduleWorkTime())){
            workNote1.setLate(1);//迟到
        }
        int num = workNoteMapper.insert(workNote1);
        if(num>0){
            rv.setInfo("签到成功");
            rv.setSuccess(true);
        }else {
            rv.setInfo("签到失败，请重新尝试");
        }
        return rv;
    }

    /**
     * 员工签退
     * @param user
     * @return
     */
    @Override
    public ResultVo addQuitTime(User user) {
        int userId = user.getUserId();
        int departmentId = user.getDepartmentId();
        ResultVo rv = new ResultVo();
        System.out.println(userId);
        System.out.println(departmentId);
        QueryWrapper<WorkNote> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        //倒序查询
        qw.orderByDesc("date");
        //存储该用户的所有记录
        List<WorkNote> workNoteList = workNoteMapper.selectList(qw);

        //如果没有考勤记录
        if(workNoteList.size()==0){
            WorkNote workNote = new WorkNote();
            workNote.setUserId(userId);
            workNote.setUserName(user.getUserName());
            workNote.setDate(LocalDate.now());
            LocalDateTime nowTime1= LocalDateTime.now();
            workNote.setWorkTime(nowTime1);
            workNote.setLack(1);
            workNote.setEarly(0);
            workNote.setLate(0);

            //获取签到时间标准
            QueryWrapper<Schedule> qw1 = new QueryWrapper<>();
            qw1.eq("department_id", departmentId);
            Schedule schedule = scheduleMapper.selectOne(qw1);
            String nowTime2 = nowTime1.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
            String quitTime = schedule.getScheduleQuitTime().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
            //如果员工迟到  nowTime.isAfter()在设定的时间之后
            if(nowTime2.compareTo(quitTime)<0){
                workNote.setEarly(1);//迟到
                System.out.println("早退");
            }
            int num = workNoteMapper.insert(workNote);
            System.out.println(workNote);
            if(num>0){
                rv.setInfo("签退成功");
                rv.setSuccess(true);
            }else {
                rv.setInfo("签退失败，请重新尝试");
            }
            return rv;
        }

        //最新记录
        WorkNote workNote = workNoteList.get(0);
        //当前时间
        Calendar rightNow = Calendar.getInstance();
        Date nowTime = rightNow.getTime();
        //当前时间
        LocalDateTime nowTime1= LocalDateTime.now();
        //获取签退时间标准
        QueryWrapper<Schedule> qw1 = new QueryWrapper<>();
        qw1.eq("department_id", departmentId);
        Schedule schedule = scheduleMapper.selectOne(qw1);
        String nowTime2 = nowTime1.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
        String quitTime = schedule.getScheduleQuitTime().format(DateTimeFormatter.ofPattern("HH:mm:ss"));

        //如果重复签退
        if(workNote.getQuitTime()!=null && isSameDay(workNote.getQuitTime(), nowTime)){
            rv.setInfo("您今天已签退，请勿重复签退");
            rv.setSuccess(true);
            return rv;
        }

        //如果上午签过到
        if(workNote.getWorkTime()!=null && isSameDay(workNote.getWorkTime(), nowTime)){
            //更改下午签退记录
            workNote.setQuitTime(nowTime1);
            workNote.setLack(0);
            //如果早退
//            if(nowTime1.isBefore(schedule.getScheduleQuitTime())){
//
//            }
            if(nowTime2.compareTo(quitTime)<0){
                workNote.setEarly(1);
                System.out.println("早退");
            }
            QueryWrapper<WorkNote> qw2 = new QueryWrapper<>();
            qw2.eq("user_id", userId);
            qw2.eq("date", LocalDate.now());
            System.out.println(workNote);
            int num = workNoteMapper.update(workNote, qw2);
            if(num>0){
                rv.setInfo("签退成功");
                rv.setSuccess(true);
            }else {
                rv.setInfo("签退失败，请重新尝试");
            }
        }else {
            //上午没有签到，则添加签退记录
            WorkNote workNote1 = new WorkNote();
            workNote1.setUserId(userId);
            workNote1.setUserName(user.getUserName());
            workNote1.setDate(LocalDate.now());
            workNote1.setQuitTime(nowTime1);
            //上午缺一次卡
            workNote1.setLack(1);
            workNote1.setEarly(0);
            workNote1.setLate(0);
            //如果早退
            if(nowTime2.compareTo(quitTime)<0){
                workNote1.setEarly(1);
                System.out.println("早退");
            }
            int num = workNoteMapper.insert(workNote1);
            System.out.println(workNote1);
            if(num>0){
                rv.setInfo("签退成功");
                rv.setSuccess(true);
            }else {
                rv.setInfo("签退失败，请重新尝试");
            }
        }
        return rv;
    }

    /**
     * 比较是否是同一天
     * @param createTime
     * @return
     * @throws ParseException
     */
    public boolean isSameDay(LocalDateTime createTime, Date nowTime){
        String toString = createTime.toString();
        String replace = toString.replace("T", " ");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Calendar rightNow = Calendar.getInstance();//当前时间
//        Date dayOne = rightNow.getTime();
        Date parse = null;
        try {
            parse = dateFormat.parse(replace);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return DateUtils.isSameDay(nowTime, parse);
    }

    /**
     * 查询考勤记录
     * @param workNote
     * @return
     */
    @Override
    public ResultVo selectAttendanceRecords(WorkNote workNote) {
        ResultVo rv = new ResultVo();
        System.out.println(workNote);
        Page<WorkNote> page = new Page<>(workNote.getPage(), workNote.getRow());
        QueryWrapper<WorkNote> qw = new QueryWrapper<>();
        qw.eq(StringUtils.isNotEmpty(workNote.getUserName()), "user_name", workNote.getUserName());
        qw.between(workNote.getWorkTime()!=null && workNote.getQuitTime()!=null,
                "date", workNote.getWorkTime(), workNote.getQuitTime());
        if(workNote.getWorkTime()!=null && workNote.getQuitTime()!=null && workNote.getWorkTime().isAfter(workNote.getQuitTime())){
            rv.setInfo("结束日期不能比开始日期早！");
            return rv;
        }
//        qw.eq(workNote.getEarly()!=null, "early", workNote.getEarly());
//        qw.eq(workNote.getLate()!=null, "late", workNote.getLate());
        Page<WorkNote> myPage = workNoteMapper.selectPage(page, qw);
        Map<String, Object> map = new HashMap<>();
        //当前页集合
        map.put("list", myPage);
        //总页数
        map.put("totalPage", myPage.getPages());
        //总条数
        map.put("total", myPage.getTotal());
        rv.setSuccess(true);
        rv.setData(map);
        return rv;
    }

}









